<?php

namespace App\Admin\Actions\Keyword;

use App\Miya\Models\Classify;
use App\Miya\Models\Info;
use App\Miya\Models\Module;
use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;

class AutoSelect extends Action
{
    protected $selector = '.auto-select';

    public function handle(Request $request)
    {
        $types = $request->get('type');
        if (in_array('module', $types)) {
            Module::all()->each(function ($module) {
                $module->keyword_id = app('admin_keyword')->autoSelect('modules')->id;
                $module->save();
            });
        }
        if (in_array('classify', $types)) {
            Classify::all()->each(function ($classify) {
                $classify->keyword_id = app('admin_keyword')->autoSelect('classifies')->id;
                $classify->save();
            });
        }
        if (in_array('info', $types)) {
            Info::all()->each(function ($info) {
                $info->keyword_id = app('admin_keyword')->autoSelect('infos')->id;
                $info->save();
            });
        }

        return $this->response()->success('关键词适配完成!')->refresh();
    }

    public function form()
    {
        $type = [
            'module' => '模块',
            'classify' => '分类',
            'info' => '信息',
        ];

        $this->checkbox('type', '类型')->options($type)
            ->help('请选择需要适配关键词的范围 <p class="text-red">已上线的网站重新适配关键词可能影响现有网站排名,请慎重操作!</p>')
            ->value(['module', 'classify', 'info']);
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-success auto-select">适配关键词</a>
HTML;
    }
}
